<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>其他入库单</h3>
      <el-button type="success" size="small" @click="handleAdd">
        <i class="el-icon-plus" /> 可入库
      </el-button>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wapper">
        <div>
          <el-form
            ref="searchForm"
            :model="warehousingQuery"
            :inline="true"
            label-width="90px"
          >
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                style="width: 350px"
                @change="handleDateChange"
              />
            </el-form-item>

            <el-form-item label="商品">
              <el-select
                v-model="warehousingQuery.goodsId"
                placeholder="请选择商品"
                clearable
                style="width: 200px"
                @change="handleGoodsChanges"
              >
                <el-option
                  v-for="item in goodsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="负责人">
              <el-select
                v-model="warehousingQuery.directorId"
                placeholder="请选择负责人"
                clearable
                filterable
                remote
                :loading="directorLoading"
                :remote-method="searchDirectors"
                @focus="onDirectorFocus"
                style="width: 200px"
                @change="handleDirectorChange"
              >
                <el-option
                  v-for="item in directorList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select
                v-model="warehousingQuery.status"
                placeholder="请选择状态"
                clearable
                style="width: 150px"
                @change="handleStatusChange"
              >
                <el-option label="待审核" :value="0" />
                <el-option label="审核中" :value="1" />
                <el-option label="已审核" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-collapse-transition>

    <!-- 顶部信息区域 -->
    <div class="info-header">
      <div class="header-right">
        <el-form
          ref="searchForm"
          :model="warehousingQuery"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="负责人">
            <el-select
              v-model="warehousingQuery.directorId"
              placeholder="请选择负责人"
              clearable
              filterable
              remote
              :loading="directorLoading"
              :remote-method="searchDirectors"
              @focus="onDirectorFocus"
              style="width: 200px"
              @change="handleDirectorChange"
            >
              <el-option
                v-for="item in directorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <!-- <el-form-item label="商品">
            <el-select
              v-model="warehousingQuery.goodsId"
              placeholder="请选择商品"
              clearable
              style="width: 200px"
              @change="handleGoodsChanges"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="状态">
            <el-select
              v-model="warehousingQuery.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
              @change="handleStatusChange"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="已审核" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >
            {{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <!-- <div class="attachment-info">
            <i class="el-icon-paperclip"></i> 上传附件
            <span class="order-number">单据编号: QTRK202503210001</span>
          </div> -->
        <!-- <el-button type="success" size="small" @click="handleAdd">
            <i class="el-icon-plus"></i> 可入库
          </el-button> -->
      </div>
    </div>

    <!-- 商品列表区域 -->
    <el-table
      :data="InventoryList"
      border
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" width="70" align="center" />

      <!-- <el-table-column prop="id" label="ID" width="80"></el-table-column> -->
      <!-- 
      <el-table-column
        prop="goodsName"
        label="商品名称"
        width="150"
      /> -->

      <el-table-column label="商品明细" width="1000" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 循环渲染每个商品项 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <div class="goods-row">
                <!-- 第一行：商品名称、仓库、数量、单价 -->
                <div class="goods-name">{{ item.goodsName }}</div>
                <div class="goods-type">{{ item.warehouseName }}</div>
                <div class="goods-number">
                  数量:
                  <span class="number-value" style="color: #409eff">{{
                    item.number
                  }}</span>
                </div>
                <div class="goods-price">
                  单价:
                  <span class="price-value" style="color: #67c23a"
                    >¥{{ item.unitPrice }}</span
                  >
                </div>
                <div class="goods-tax-rate">
                  税率:
                  <span class="tax-rate-value" style="color: #e6a23c"
                    >{{ item.taxRate }}%</span
                  >
                </div>
                <div class="goods-tax-price">
                  税额:
                  <span class="tax-price-value" style="color: #f56c6c"
                    >¥{{ item.taxPrice }}</span
                  >
                </div>
                <div class="goods-total">
                  总价:
                  <span class="total-value" style="color: #409eff"
                    >¥{{ item.totalPrice }}</span
                  >
                </div>
                <div class="goods-tax-total">
                  含税:
                  <span class="tax-total-value" style="color: #f56c6c"
                    >¥{{ item.totalTaxPrice }}</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>

      <!-- <el-table-column prop="warehouseName" label="仓库名称" width="150" /> -->

      <!-- <el-table-column prop="number" label="数量" width="100" /> -->

      <!-- <el-table-column prop="unitPrice" label="单价" width="150">
        <template slot-scope="scope">
          {{ scope.row.unitPrice ? "¥" + scope.row.unitPrice : "-" }}
        </template>
      </el-table-column>

      <el-table-column prop="totalPrice" label="总价" width="150">
        <template slot-scope="scope">
          {{ scope.row.totalPrice ? "¥" + scope.row.totalPrice : "-" }}
        </template>
      </el-table-column> -->

      <el-table-column prop="status" label="状态" width="150" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>

      <el-table-column
        prop="operation"
        label="操作"
        align="center"
        width="300"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            :disabled="scope.row.status === 1"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            :disabled="scope.row.status === 1"
            type="warning"
            size="small"
            @click="handleAudit(scope.row)"
            >审核</el-button
          >
          <el-button
            type="danger"
            size="small"
            :disabled="scope.row.status === 1"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="warehousingQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="warehousingQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 操作按钮行 -->
    <div v-if="selectedRowIndex >= 0" class="table-operation-row">
      <div class="operation-buttons">
        <el-button
          type="success"
          size="mini"
          icon="el-icon-plus"
          circle
          @click="addRow"
        />
        <el-button
          type="danger"
          size="mini"
          icon="el-icon-close"
          circle
          @click="removeRow"
        />
      </div>
    </div>

    <!-- 表格底部汇总行 -->
    <!-- <div class="summary-row">
        <span class="summary-label">合计:</span>
        <div class="summary-cells"></div>
        <span class="summary-amount">{{ totalAmount.toFixed(2) }}</span>
      </div> -->

    <!-- 备注区域 -->
    <!-- <div class="remarks-section">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="若无备注信息"
          v-model="orderData.remarks"
        >
        </el-input>
      </div> -->

    <!-- 底部工具栏 -->
    <!-- <div class="footer-toolbar">
        <el-button type="text" icon="el-icon-document">
          <i class="el-icon-edit-outline"></i> 自定义字段
        </el-button>
        <div class="right-actions">
          <el-button type="text" @click="handleHistory">历史单据</el-button>
          <el-button type="text">操作日志</el-button>
        </div>
      </div> -->

    <!-- 新增弹框 -->
    <el-dialog title="编辑入库单" :visible.sync="dialogVisible" width="80%">
      <!-- 商品明细表格 -->
      <div v-if="editForm">

        <el-table
          :data="editForm.list"
          border
          style="width: 100%; margin-bottom: 20px"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column label="商品" width="150" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.goodsId"
                placeholder="请选择商品"
                style="width: 100%"
                @change="(val) => handleItemGoodsChange(val, scope.$index)"
              >
                <el-option
                  v-for="item in goodsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="仓库" width="150" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.warehouseId"
                placeholder="请选择仓库"
                style="width: 100%"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="120" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.number"
                :min="1"
                :precision="0"
                @change="(val) => calculateItemTotal(scope.$index)"
                style="width: 100%"
              />
            </template>
          </el-table-column>

          <el-table-column label="单价" width="150" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.unitPrice"
                :min="0"
                :precision="2"
                @change="(val) => calculateItemTotal(scope.$index)"
                style="width: 100%"
              />
            </template>
          </el-table-column>

          <el-table-column label="金额" width="150" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.totalPrice"
                disabled
                style="width: 100%"
              >
                <template slot="prepend">¥</template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="税率(%)" width="150" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.taxRate"
                :min="0"
                :max="100"
                :precision="2"
                @change="(val) => calculateItemTotal(scope.$index)"
                style="width: 100%"
              />
            </template>
          </el-table-column>

          <el-table-column label="税额" width="150" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.taxPrice"
                disabled
                style="width: 100%"
              >
                <template slot="prepend">¥</template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="含税总价" width="150" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.totalTaxPrice"
                disabled
                style="width: 100%"
              >
                <template slot="prepend">¥</template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                circle
                @click="removeItem(scope.$index)"
                :disabled="editForm.list.length <= 1"
              />
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-bottom: 20px">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="addItem"
            >添加商品</el-button
          >
        </div>

                <el-form
          ref="form"
          :model="editForm"
          :rules="rules"
          label-width="100px"
          style="margin-bottom: 20px"
        >
          <el-form-item label="负责人">
            <el-select
              v-model="editForm.directorId"
              placeholder="请选择负责人"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in directorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="editForm.remark"
              type="textarea"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>

        <!-- 每个订单的摘要信息 -->
        <!-- <div class="order-summary">
          <span>数量合计: {{ calculateTotalQuantity() }}</span>
          <span>金额合计: ¥{{ formatNumber(calculateTotalAmount()) }}</span>
          <span>含税合计: ¥{{ formatNumber(calculateTotalTaxAmount()) }}</span>
        </div> -->
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 可入库列表弹框 -->
    <el-dialog
      title="可入库列表"
      :visible.sync="enterWarehouseDialogVisible"
      width="80%"
    >
      <!-- 调试信息 -->
      <div style="margin-bottom: 10px">
        <small
          >数据条数:
          {{ enterWarehouseList ? enterWarehouseList.length : 0 }}</small
        >
      </div>

      <!-- 有数据时显示列表 -->
      <el-table
        v-if="enterWarehouseList && enterWarehouseList.length > 0"
        ref="enterWarehouseTable"
        :data="enterWarehouseList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        @selection-change="handleEnterWarehouseSelectionChange"
      >
        <!-- 多选框列 -->
        <el-table-column type="selection" width="55" align="center" />

        <!-- 主数据列 -->
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column
          prop="directorName"
          label="负责人"
          width="100"
          align="center"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            {{ formatCreateTime(scope.row.createTime) }}
          </template>
        </el-table-column>

        <!-- 商品明细列 -->
        <el-table-column label="商品明细" min-width="800" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.list && scope.row.list.length > 0">
              <el-table :data="scope.row.list" border style="width: 100%">
                <el-table-column
                  label="商品"
                  width="120"
                  align="center"
                  prop="goodsName"
                />
                <el-table-column
                  label="仓库"
                  width="120"
                  align="center"
                  prop="warehouseName"
                />
                <el-table-column
                  label="数量"
                  width="80"
                  align="center"
                  prop="number"
                />
                <el-table-column label="单价" width="100" align="center">
                  <template slot-scope="subScope">
                    {{
                      subScope.row.unitPrice
                        ? "¥" + subScope.row.unitPrice
                        : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="总价" width="100" align="center">
                  <template slot-scope="subScope">
                    {{
                      subScope.row.totalPrice
                        ? "¥" + subScope.row.totalPrice
                        : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="税率" width="80" align="center">
                  <template slot-scope="subScope">
                    {{
                      subScope.row.taxRate ? subScope.row.taxRate + "%" : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="税额" width="100" align="center">
                  <template slot-scope="subScope">
                    {{
                      subScope.row.taxPrice ? "¥" + subScope.row.taxPrice : "-"
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="含税总价" width="120" align="center">
                  <template slot-scope="subScope">
                    {{
                      subScope.row.totalTaxPrice
                        ? "¥" + subScope.row.totalTaxPrice
                        : "-"
                    }}
                  </template>
                </el-table-column>
              </el-table>

              <!-- 每个订单的摘要信息 -->
              <div class="order-summary">
                <span
                  >数量合计: {{ calculateTotalQuantity(scope.row.list) }}</span
                >
                <span
                  >金额合计: ¥{{
                    formatNumber(calculateTotalAmount(scope.row.list))
                  }}</span
                >
                <span
                  >含税合计: ¥{{
                    formatNumber(calculateTotalTaxAmount(scope.row.list))
                  }}</span
                >
              </div>
            </div>
            <div v-else class="empty-data">
              <i class="el-icon-document"></i>
              <p>暂无商品明细</p>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="remark"
          label="备注"
          width="150"
          align="center"
        />

        <!-- 单个操作列 -->
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEnterWarehouse(scope.row)"
              >入库</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量入库操作统计区域 -->
      <div
        v-if="selectedEnterWarehouseItems.length > 0"
        class="selected-summary"
      >
        <div class="selected-info">
          已选择 {{ selectedEnterWarehouseItems.length }} 条记录
        </div>
      </div>

      <!-- 没有数据时显示提示 -->
      <div
        v-if="!enterWarehouseList || enterWarehouseList.length === 0"
        class="no-data"
      >
        <i class="el-icon-circle-close"></i>
        <p>没有可入库的数据</p>
      </div>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="enterWarehouseDialogVisible = false"
          >取 消</el-button
        >
        <el-button
          type="primary"
          :disabled="selectedEnterWarehouseItems.length === 0"
          @click="handleEnterWarehouseSubmit"
          >批量入库</el-button
        >
      </div>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="审核" :visible.sync="auditDialogVisible" width="400px">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="备注">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selCanEnterWarehouseListApi,
  selEnterWarehouseListApi,
  addEnterWarehouseApi,
  updateEnterWarehouseByIdApi,
  delEnterWarehouseByIdApi,
  handleEnterWarehouseByIdApi,
} from "@/api/warehouse";
import { selGoodsListApi, selGoodsByIdApi } from "@/api/goods";
import { selWarehouseListApi, selStaffListApi } from "@/api/system";
export default {
  name: "OtherWarehouseReceipts",
  data() {
    return {
      orderData: {
        supplier: "",
        salesperson: "",
        orderDate: new Date().toISOString().substr(0, 10),
        businessCategory: "other_in",
        businessType: "other",
        remarks: "",
      },
      tableData: [
        {
          productName: "",
          productCategory: "",
          brand: "",
          attributes: "",
          unit: "",
          warehouse: "",
          availableStorage: 0,
          quantity: 1,
          packageInfo: "",
          unitPrice: "",
          amount: "",
        },
      ],
      salesPersonOptions: [
        { value: "person1", label: "张三" },
        { value: "person2", label: "李四" },
        { value: "person3", label: "王五" },
      ],
      warehouseOptions: [
        { value: "wh1", label: "默认仓库" },
        { value: "wh2", label: "冷藏仓库" },
        { value: "wh3", label: "食品仓库" },
      ],
      scanEnabled: false,
      selectedRowIndex: -1,
      totalAmount: 0,
      isFilterVisible: false, // 控制筛选框的显示与隐藏
      dialogVisible: false,
      editForm: {
        id: "",
        directorId: "",
        operatorId: "",
        remark: "",
        status: "",
        list: [], // 深拷贝list数组
      },
      // 商品查询参数
      goodsQuery: {
        goodsTypeId: null,
        name: "",
        page: 1,
        pageSize: 10,
        supplierId: null,
        warehouseId: null,
      },
      // 仓库列表查询
      warehouseQuery: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      // 入库单查询
      warehousingQuery: {
        directorId: "",
        endTime: "",
        goodsId: "",
        page: 1,
        pageSize: 10,
        startTime: "",
        status: "",
      },
      InventoryList: [], // 入库单列表
      rules: {
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        warehouseId: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
        number: [{ required: true, message: "请输入数量", trigger: "blur" }],
        unitPrice: [{ required: true, message: "请输入单价", trigger: "blur" }],
      },
      goodsList: [], // 商品列表
      selectedGoodsInfo: null, // 存储选中的商品详情
      enterWarehouseDialogVisible: false, // 可入库列表弹框显示状态
      enterWarehouseList: [], // 可入库列表数据
      selectedEnterWarehouseItems: [], // 存储选中的项
      auditDialogVisible: false,
      auditForm: {
        id: null,
        operatorId: "", // 当前登录用户ID
        remark: "",
      },
      // 入库单查询参数
      queryParams: {
        goodsId: "",
        directorId: "",
        status: "",
        startTime: "",
        endTime: "",
      },
      // 职员列表
      staffQuery: {
        page: 1,
        pageSize: 10,
        name: "",
        mobile: "",
        parent: "",
      },
      dateRange: [], // 日期范围
      directorList: [], // 审核人列表
      directorLoading: false,
      searchDirectors: null,
      onDirectorFocus: null,
    };
  },
  watch: {
    tableData: {
      handler: function (val) {
        this.calculateTotal();
      },
      deep: true,
    },
    "editForm.number": {
      handler(newVal) {
        const number = parseFloat(newVal) || 0;
        const unitPrice = parseFloat(this.editForm.unitPrice) || 0;
        this.editForm.totalPrice = (number * unitPrice).toFixed(2);
      },
      immediate: true, // 立即执行
    },
    "editForm.unitPrice": {
      handler(newVal) {
        const unitPrice = parseFloat(newVal) || 0;
        const number = parseFloat(this.editForm.number) || 0;
        this.editForm.totalPrice = (number * unitPrice).toFixed(2);
      },
      immediate: true, // 立即执行
    },
  },
  created() {
    this.selGoodsList(); // 获取商品列表
    this.selWarehouseList(); // 获取仓库列表
    this.selEnterWarehouseList(); // 获取入库单列表
    this.selDirectorList();
    this.selStaffList();
  },
  methods: {
    // 获取可新建的入库单查询
    async selCanEnterWarehouseList() {
      try {
        const res = await selCanEnterWarehouseListApi();
        if (res.code === 1) {
          this.enterWarehouseList = res.data || [];
          this.enterWarehouseDialogVisible = true;
        } else {
          this.$message.error(res.msg || "获取可入库列表失败");
        }
      } catch (error) {
        console.error("获取可入库列表失败:", error);
        this.$message.error("获取可入库列表失败");
      }
    },
    // 获取商品列表
    async selGoodsList() {
      const res = await selGoodsListApi(this.goodsQuery);
      this.goodsList = res.records || [];
    },
    // 获取仓库列表
    async selWarehouseList() {
      const res = await selWarehouseListApi(this.warehouseQuery);
      this.warehouseList = res.records || [];
    },
    // 职工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery);
      this.directorList = res.records || [];
    },
    // 点击历史单据
    handleHistory() {
      this.$router.push({
        name: "OtherWarehouseReceiptsHistoricalDocuments",
      });
    },
    openSupplierSelector() {
      // 打开供应商选择器
      this.$message("打开供应商选择器");
    },
    handleProductSelect(index, row) {
      // 记录当前选中行索引
      this.selectedRowIndex = index;
      // 模拟选择商品后的数据填充
      this.$set(this.tableData[index], "productName", "商品" + (index + 1));
      this.$set(this.tableData[index], "productCategory", "食品");
      this.$set(this.tableData[index], "brand", "品牌" + (index + 1));
      this.$set(this.tableData[index], "attributes", "常温");
      this.$set(this.tableData[index], "unit", "个");
      this.$set(this.tableData[index], "availableStorage", 100);
    },
    addRow() {
      const newIndex = this.selectedRowIndex + 1;
      this.tableData.splice(newIndex, 0, {
        productName: "",
        productCategory: "",
        brand: "",
        attributes: "",
        unit: "",
        warehouse: "",
        availableStorage: 0,
        quantity: 1,
        packageInfo: "",
        unitPrice: "",
        amount: "",
      });
      this.selectedRowIndex = newIndex;
    },
    removeRow() {
      if (this.tableData.length > 1) {
        this.tableData.splice(this.selectedRowIndex, 1);
        this.selectedRowIndex = Math.min(
          this.selectedRowIndex,
          this.tableData.length - 1
        );
      } else {
        this.$message.warning("至少保留一行");
      }
    },
    calculateRowAmount(row) {
      if (row.quantity && row.unitPrice) {
        row.amount = (
          parseFloat(row.quantity) * parseFloat(row.unitPrice)
        ).toFixed(2);
      }
      this.calculateTotal();
    },
    calculateUnitPrice(row) {
      if (row.amount && row.quantity) {
        row.unitPrice = (
          parseFloat(row.amount) / parseFloat(row.quantity)
        ).toFixed(2);
      }
    },
    calculateTotal() {
      if (!this.editForm) return;

      const number = parseFloat(this.editForm.number) || 0;
      const unitPrice = parseFloat(this.editForm.unitPrice) || 0;
      const taxRate = parseFloat(this.editForm.taxRate) || 0;

      // Calculate total price without tax
      const totalPrice = number * unitPrice;
      this.editForm.totalPrice = totalPrice.toFixed(2);

      // Calculate tax amount
      const taxPrice = totalPrice * (taxRate / 100);
      this.editForm.taxPrice = taxPrice.toFixed(2);

      // Calculate total price with tax
      const totalTaxPrice = totalPrice + taxPrice;
      this.editForm.totalTaxPrice = totalTaxPrice.toFixed(2);
    },
    // 表单验证
    validateForm() {
      if (!this.selectedGoods?.id) {
        this.$message.warning("请选择商品");
        return false;
      }
      if (!this.orderData.warehouse) {
        this.$message.warning("请选择仓库");
        return false;
      }
      if (!this.orderData.quantity || this.orderData.quantity <= 0) {
        this.$message.warning("请输入有效的数量");
        return false;
      }
      if (!this.orderData.unitPrice || this.orderData.unitPrice <= 0) {
        this.$message.warning("请输入有效的单价");
        return false;
      }
      return true;
    },
    // 重置表单
    resetForm() {
      this.orderData = {
        supplier: "",
        warehouse: "",
        quantity: 1,
        unitPrice: "",
        remarks: "",
      };
      this.selectedGoods = null;
      this.totalAmount = 0;
    },
    // 点击新增按钮
    handleAdd() {
      this.selCanEnterWarehouseList();
    },
    // 处理数量输入实时更新
    handleNumberInput(value) {
      if (!value || !this.editForm.unitPrice) {
        this.editForm.totalPrice = 0;
        return;
      }

      const number = parseFloat(value);
      const unitPrice = parseFloat(this.editForm.unitPrice);

      if (!isNaN(number) && !isNaN(unitPrice)) {
        this.editForm.totalPrice = (number * unitPrice).toFixed(2);
      }
    },

    // 处理单价变化
    handlePriceChange(value) {
      if (!value || !this.editForm.number) {
        this.editForm.totalPrice = 0;
        return;
      }

      const number = parseFloat(this.editForm.number);
      const unitPrice = parseFloat(value);

      if (!isNaN(number) && !isNaN(unitPrice)) {
        this.editForm.totalPrice = (number * unitPrice).toFixed(2);
      }
    },

    // 商品选择变化时的处理
    async handleGoodsChange(goodsId) {
      if (!goodsId) {
        this.selectedGoodsInfo = null;
        this.editForm.unitPrice = "";
        this.editForm.totalPrice = 0;
        return;
      }

      try {
        const res = await selGoodsByIdApi(goodsId);
        if (res.code === 1) {
          this.selectedGoodsInfo = res.data;
          if (this.selectedGoodsInfo) {
            // 设置单价
            this.editForm.unitPrice = this.selectedGoodsInfo.price || "";
            // 自动计算总价
            this.handleNumberInput(this.editForm.number);
          }
        } else {
          this.$message.error(res.msg || "获取商品信息失败");
        }
      } catch (error) {
        console.error("获取商品信息失败:", error);
        this.$message.error("获取商品信息失败");
      }
    },
    // 获取入库单列表
    async selEnterWarehouseList() {
      try {
        const res = await selEnterWarehouseListApi(this.warehousingQuery);
        this.InventoryList = res.records || [];
        this.total = res.total || 0;
      } catch (error) {
        console.error("获取入库单列表失败:", error);
        this.$message.error("获取入库单列表失败");
      }
    },
    // 订单选择事件处理
    handleOrderSelection(order, isSelected) {
      if (isSelected) {
        // 如果选中，添加到已选列表
        this.selectedEnterWarehouseItems.push(order);
      } else {
        // 如果取消选中，从已选列表中移除
        this.selectedEnterWarehouseItems =
          this.selectedEnterWarehouseItems.filter(
            (item) => item.id !== order.id
          );
      }
    },

    // 批量入库提交
    async handleEnterWarehouseSubmit() {
      try {
        if (this.selectedEnterWarehouseItems.length === 0) {
          this.$message.warning("请至少选择一个订单");
          return;
        }

        const loading = this.$loading({
          lock: true,
          text: "正在提交...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        // 构造API所需的参数 - 注意这是一个数组
        const paramsArray = this.selectedEnterWarehouseItems.map((order) => ({
          buyGoodsId: order.id,
          directorId: order.directorId || "",
          list: order.list.map((item) => ({
            goodsId: parseInt(item.goodsId),
            number: parseInt(item.number),
            taxPrice: parseFloat(item.taxPrice),
            taxRate: parseFloat(item.taxRate),
            totalPrice: parseFloat(item.totalPrice),
            totalTaxPrice: parseFloat(item.totalTaxPrice),
            unitPrice: parseFloat(item.unitPrice),
            warehouseId: parseInt(item.warehouseId),
          })),
          operatorId: this.$store.getters.userId || "",
          remark: order.remark || "",
        }));

        try {
          // 使用数组作为参数调用API
          const res = await addEnterWarehouseApi(paramsArray);

          loading.close();

          if (res.code === 1) {
            this.$message.success("批量入库成功");
            this.enterWarehouseDialogVisible = false;
            this.selectedEnterWarehouseItems = []; // 清空选中列表
            this.selEnterWarehouseList(); // 刷新列表
          } else {
            this.$message.error(`入库失败: ${res.msg || "未知错误"}`);
          }
        } catch (error) {
          loading.close();
          console.error("批量入库失败:", error);
          this.$message.error(`批量入库失败: ${error.message || "未知错误"}`);
        }
      } catch (error) {
        console.error("批量入库失败:", error);
        this.$message.error(`批量入库失败: ${error.message || "未知错误"}`);
      }
    },

    // 单个订单入库
    handleEnterWarehouse(order) {
      this.selectedEnterWarehouseItems = [order];
      this.handleEnterWarehouseSubmit();
    },
    // 格式化状态
    getStatusType(status) {
      const statusMap = {
        0: "warning",
        1: "success",
      };
      return statusMap[status] || "info";
    },

    // 格式化状态文本
    getStatusText(status) {
      const statusMap = {
        0: "待审核",
        1: "已审核",
      };
      return statusMap[status] || "未知状态";
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.warehousingQuery.page = val;
      this.selEnterWarehouseList();
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.warehousingQuery.pageSize = val;
      this.selEnterWarehouseList();
    },
    // 格式化时间
    formatDateTime(timestamp) {
      if (!timestamp) return "-";
      const date = new Date(timestamp);
      return date.toLocaleString();
    },

    // 点击编辑按钮
    async handleEdit(row) {
      // 复制整个行数据，包括list数组
      this.editForm = {
        id: row.id,
        directorId: row.directorId,
        operatorId: row.operatorId,
        remark: row.remark,
        status: row.status,
        list: row.list ? JSON.parse(JSON.stringify(row.list)) : [], // 深拷贝list数组
      };

      // 如果list为空，添加一个空项
      if (!this.editForm.list || this.editForm.list.length === 0) {
        this.editForm.list = [
          {
            goodsId: "",
            warehouseId: "",
            number: 1,
            unitPrice: 0,
            totalPrice: 0,
            taxRate: 0,
            taxPrice: 0,
            totalTaxPrice: 0,
          },
        ];
      }

      this.dialogVisible = true;
    },

    // 计算单个商品项的金额
    calculateItemTotal(index) {
      const item = this.editForm.list[index];
      if (!item) return;
      
      // Parse as numbers to ensure correct calculation
      const number = parseInt(item.number) || 0;
      const unitPrice = parseFloat(item.unitPrice) || 0;
      const taxRate = parseFloat(item.taxRate) || 0;
      
      // Calculate total price without tax
      const totalPrice = number * unitPrice;
      item.totalPrice = totalPrice.toFixed(2);
      
      // Calculate tax amount
      const taxPrice = totalPrice * (taxRate / 100);
      item.taxPrice = taxPrice.toFixed(2);
      
      // Calculate total price with tax
      const totalTaxPrice = totalPrice + taxPrice;
      item.totalTaxPrice = totalTaxPrice.toFixed(2);
    },

    // 商品选择变化时的处理
    async handleItemGoodsChange(goodsId, index) {
      const item = this.editForm.list[index];
      if (!goodsId || !item) {
        return;
      }

      try {
        const res = await selGoodsByIdApi(goodsId);
        if (res.code === 1) {
          const goodsInfo = res.data;
          if (goodsInfo) {
            // 设置单价
            item.unitPrice = goodsInfo.price || 0;
            // 自动计算总价
            this.calculateItemTotal(index);
          }
        } else {
          this.$message.error(res.msg || "获取商品信息失败");
        }
      } catch (error) {
        console.error("获取商品信息失败:", error);
        this.$message.error("获取商品信息失败");
      }
    },

    // 添加商品项
    addItem() {
      this.editForm.list.push({
        goodsId: "",
        warehouseId: "",
        number: 1,
        unitPrice: 0,
        totalPrice: 0,
        taxRate: 0,
        taxPrice: 0,
        totalTaxPrice: 0,
      });
    },

    // 移除商品项
    removeItem(index) {
      if (this.editForm.list.length > 1) {
        this.editForm.list.splice(index, 1);
      } else {
        this.$message.warning("至少需要保留一项商品");
      }
    },

    // 计算总数量
    calculateTotalQuantity() {
      if (!this.editForm.list || this.editForm.list.length === 0) return 0;
      return this.editForm.list.reduce(
        (total, item) => total + (parseFloat(item.number) || 0),
        0
      );
    },

    // 计算总金额（不含税）
    calculateTotalAmount() {
      if (!this.editForm.list || this.editForm.list.length === 0) return 0;
      return this.editForm.list.reduce(
        (total, item) => total + (parseFloat(item.totalPrice) || 0),
        0
      );
    },

    // 计算含税总金额
    calculateTotalTaxAmount() {
      if (!this.editForm.list || this.editForm.list.length === 0) return 0;
      return this.editForm.list.reduce(
        (total, item) => total + (parseFloat(item.totalTaxPrice) || 0),
        0
      );
    },

    // 格式化数字为两位小数
    formatNumber(num) {
      return parseFloat(num).toFixed(2);
    },

    // 保存编辑
    async handleSave() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            // Ensure correct data types according to the API documentation
            const params = {
              id: parseInt(this.editForm.id), // Ensure integer
              buyGoodsId: this.editForm.buyGoodsId ? parseInt(this.editForm.buyGoodsId) : undefined,
              directorId: this.editForm.directorId || "",
              operatorId: this.$store.getters.userId || "",
              remark: this.editForm.remark || "",
              list: this.editForm.list.map(item => ({
                goodsId: parseInt(item.goodsId), // integer
                warehouseId: parseInt(item.warehouseId), // integer
                number: parseInt(item.number), // integer
                unitPrice: parseFloat(item.unitPrice), // number
                totalPrice: parseFloat(item.totalPrice), // number
                taxRate: parseFloat(item.taxRate), // number
                taxPrice: parseFloat(item.taxPrice), // number
                totalTaxPrice: parseFloat(item.totalTaxPrice), // number
              }))
            };
            
            // Use the id as a path parameter according to the API docs
            const res = await updateEnterWarehouseByIdApi(params, this.editForm.id);
            if (res.code === 1) {
              this.$message.success("编辑成功");
              this.dialogVisible = false;
              this.selEnterWarehouseList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "更新失败");
            }
          } catch (error) {
            console.error("更新失败:", error);
            this.$message.error("更新失败");
          }
        }
      });
    },

    // 删除
    handleDelete(id) {
      this.$confirm("确认删除该入库记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await delEnterWarehouseByIdApi(id);
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.selEnterWarehouseList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          // this.$message.info("已取消删除");
        });
    },

    // 处理审核按钮点击
    handleAudit(row) {
      this.auditForm = {
        id: row.id,
        operatorId: "", // 从vuex获取当前用户ID
        remark: "",
      };
      this.auditDialogVisible = true;
    },

    // 提交审核
    async submitAudit() {
      try {
        const res = await handleEnterWarehouseByIdApi({
          id: this.auditForm.id,
          operatorId: this.auditForm.operatorId,
          remark: this.auditForm.remark,
        });

        if (res.code === 1) {
          this.$message.success("审核成功");
          this.auditDialogVisible = false;
          this.selEnterWarehouseList(); // 刷新列表
        } else {
          this.$message.error(res.msg || "审核失败");
        }
      } catch (error) {
        console.error("审核失败:", error);
        this.$message.error("审核失败");
      }
    },
    selDirectorList() {
      // 实现获取负责人列表的逻辑
    },
    // 商品改变
    handleGoodsChanges(val) {
      this.selEnterWarehouseList();
    },
    // 负责人改变
    handleDirectorChange(val) {
      this.selEnterWarehouseList();
    },
    // 状态改变
    handleStatusChange(val) {
      this.selEnterWarehouseList();
    },
    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0]);
        startDate.setHours(0, 0, 0, 0);
        this.warehousingQuery.startTime = Math.floor(
          startDate.getTime() / 1000
        );

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1]);
        endDate.setHours(23, 59, 59, 999);
        this.warehousingQuery.endTime = Math.floor(endDate.getTime() / 1000);
      } else {
        this.warehousingQuery.startTime = "";
        this.warehousingQuery.endTime = "";
      }
    },
    handleSearch() {
      // 处理查询的逻辑
      this.selEnterWarehouseList();
    },
    // 重置
    handleReset() {
      // 处理重置的逻辑
      this.warehousingQuery = {
        goodsId: "",
        directorId: "",
        status: "",
        startTime: "",
        endTime: "",
        page: 1,
        pageSize: 10,
      };
      this.dateRange = [];
      this.selEnterWarehouseList();
    },
    // 格式化数字为金额形式
    formatNumber(num) {
      if (!num) return "0.00";
      return parseFloat(num).toFixed(2);
    },

    // 计算总数量
    calculateTotalQuantity(items) {
      if (!items || !items.length) return 0;
      return items.reduce((sum, item) => sum + (Number(item.number) || 0), 0);
    },

    // 计算总金额
    calculateTotalAmount(items) {
      if (!items || !items.length) return 0;
      return items.reduce(
        (sum, item) => sum + (Number(item.totalPrice) || 0),
        0
      );
    },

    // 计算含税总金额
    calculateTotalTaxAmount(items) {
      if (!items || !items.length) return 0;
      return items.reduce(
        (sum, item) => sum + (Number(item.totalTaxPrice) || 0),
        0
      );
    },

    // 表格多选框选择变化处理
    handleEnterWarehouseSelectionChange(selection) {
      this.selectedEnterWarehouseItems = selection;
    },

    // 格式化创建时间
    formatCreateTime(timestamp) {
      if (!timestamp) return "-";

      // 时间戳可能是秒级的，需要转换为毫秒级
      const date = new Date(timestamp * 1000);

      // 格式化为YYYY-MM-DD HH:MM:SS
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 处理负责人选择获取焦点事件
    onDirectorFocus() {
      this.directorLoading = true;
      this.searchDirectors("");
    },
    // 搜索负责人方法
    async searchDirectors(query) {
      try {
        const res = await selStaffListApi({
          page: 1,
          pageSize: 9999,
          name: query,
        });

        this.directorList = res.records || [];
      } catch (error) {
        console.error("搜索负责人失败:", error);
        this.$message.error("搜索负责人失败");
        this.directorList = [];
      } finally {
        this.directorLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 商品明细样式 */
.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-row {
  display: flex;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
}

.goods-name {
  width: 150px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-type {
  width: 120px;
  color: #606266;
}

.goods-number,
.goods-price,
.goods-tax-rate,
.goods-tax-price,
.goods-total,
.goods-tax-total {
  width: 100px;
  color: #606266;
  margin-right: 10px;
}

.number-value,
.price-value,
.tax-rate-value,
.tax-price-value,
.total-value,
.tax-total-value {
  color: #409eff;
  font-weight: 500;
}

.no-goods {
  color: #909399;
  padding: 10px 0;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

/* 订单容器样式 */
.order-container {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 订单头部样式 */
.order-header {
  display: flex;
  justify-content: space-between;
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.order-time {
  font-weight: bold;
  color: #303133;
}

.order-person {
  color: #606266;
}

.order-selection {
  margin-left: auto;
}

/* 订单摘要信息 */
.order-summary {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  background-color: #f8f8f8;
  border-top: 1px solid #ebeef5;
}

.order-summary span {
  margin-left: 20px;
  font-weight: bold;
  color: #606266;
}

.order-summary span:last-child {
  color: #f56c6c;
}

/* 空数据提示 */
.empty-data,
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: #909399;
}

.empty-data i,
.no-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-data p,
.no-data p {
  margin: 0;
  font-size: 14px;
}

/* 批量入库操作统计区域 */
.selected-summary {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  background-color: #f8f8f8;
  border-top: 1px solid #ebeef5;
}

.selected-info {
  color: #606266;
  font-weight: bold;
}
</style>
